angular.module('RDash')
    .controller('TMessageDialogCtrl', ['$scope', '$uibModalInstance', 'title', 'content', function ($scope, $uibModalInstance, title, content) {
        $scope.title = title;
        $scope.content = content;

        $scope.submit = function () {
            $uibModalInstance.close();
        };
        $scope.cancel = function () {
            $uibModalInstance.dismiss();
        };
    }])
    .controller('LogCtrl', ['app', 'restService', 'commonService', '$scope', function (app, restService, commonService, $scope) {
        console.log('log-ctrl');
        app.setCurUrl('/log');

        $scope.actionLogQuery = commonService.createPageQuery(1, 10, 5);
        $scope.queryLog = function (page) {
            $scope.actionLogQuery.setPage(page);
            restService.api.log.save({
                ID: 'queryActionLogs'
            }, {
                'page': $scope.actionLogQuery.page,
                'pageSize': $scope.actionLogQuery.pageSize
            }, function (result) {
                if (app.catchResultCode(result['resultCode'])) {
                    $scope.actionLogQuery.catchResult(result);
                    console.log($scope.actionLogQuery);
                }
            });
        };

        $scope.queryLog(1);
    }])
    .controller('MembersCtrl', ['app', 'restService', '$scope', '$http', '$location', '$uibModal', '$window', 'commonService', "templateService", function (app, restService, $scope, $http, $location, $uibModal, $window, commonService, templateService) {
        console.log('members-ctrl');
        app.setCurUrl('/members');

        $scope.userQuery = commonService.createPageQuery(1, 10, 5);

        $scope.listUsers = function (page) {
            $scope.userQuery.setPage(page);
            $http({
                method: 'POST',
                url: restService.create('user/listUsers'),
                data: {
                    page: $scope.userQuery.page,
                    pageSize: $scope.userQuery.pageSize
                }
            }).then(function successCallback(response) {
                if (app.catchResultCode(response.data['resultCode'])) {
                    $scope.userQuery.catchResult(angular.fromJson(response.data));
                    console.log($scope.userQuery);
                }
            }, function errorCallback(response) {

            });
        };

        // 修改信息
        $scope.alterAuthorize = function (u) {
            var modalInstance = $uibModal.open({
                templateUrl: 'templates/template_member_alter.html',
                controller: 'TMemberAlterCtrl',
                backdrop: 'static',
                resolve: {
                    u: u
                }
            });

            modalInstance.result.then(function (roleIds) {
                restService.api.authorize.save({
                    ID: 'authorizeRoles'
                }, {
                    username: u.username,
                    roleIds: roleIds
                }, function (result) {
                    if (app.catchResultCode(result['resultCode'])) {
                        commonService.toast.success("授权成功!");
                    }
                });
            }, function () {

            });
        };

        $scope.setNewPassword = function (u) {
            templateService.resetPassword(u.username);
        };

        $scope.listUsers(1);
    }])
    .controller('TMemberAlterCtrl', ['app', 'restService', '$scope', '$uibModalInstance', 'u', function (app, restService, $scope, $uibModalInstance, u) {
        $scope.u = u;
        $scope.showRoles = false;
        $scope.roleRelations = [];
        $scope.roles = [];

        $scope.updateShowRoles = function () {
            $scope.showRoles = !$scope.showRoles;
        };

        $scope.trashRoleRelation = function (roleRelation) {
            $scope.roles.push({
                id: roleRelation.roleId,
                name: roleRelation.roleName,
                type: roleRelation.roleType,
                description: roleRelation.roleDescription
            });
            $scope.roleRelations.splice($scope.roleRelations.indexOf(roleRelation), 1);
        };

        $scope.authorizeRole = function (role) {
            $scope.roleRelations.push({
                roleId: role.id,
                roleName: role.name,
                roleType: role.type,
                roleDescription: role.description
            });
            $scope.roles.splice($scope.roles.indexOf(role), 1);
        };

        $scope.update = function () {
            var roleIds = [];
            angular.forEach($scope.roleRelations, function (roleRelation) {
                roleIds.push(roleRelation.roleId);
            });
            $uibModalInstance.close(roleIds);
        };
        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };

        restService.api.authorize.save({
            ID: 'listRoleRelations'
        }, {
            username: u.username
        }, function (result) {
            if (app.catchResultCode(result['resultCode'])) {
                console.log(result.data);
                $scope.roleRelations = result.data;
            }
        });

        restService.api.authorize.save({
            ID: 'unauthorizedRoles',
            username: u.username
        }, null, function (result) {
            if (app.catchResultCode(result['resultCode'])) {
                $scope.roles = result.data;
            }
        });
    }])
    // 实现动态绑定的Controller
    .controller('IncludeCtrl', ['app', '$scope', '$location', '$http', function (app, $scope, $location, $http) {
        console.log('include-ctrl');

        /*
         * 初始化时需要手动设置,
         * 因为此时的$on不能够监听到信息
         */
        $scope.include_path = app.include_path;

        // 如果include_path没有值,将返回默认页面
        if ($scope.include_path == null || $scope.include_path.toString().length == 0) {
            $location.path('/');
        }

        $scope.$on('include_path', function (d, include_path) {
            console.log('on include_path...');

            $scope.include_path = include_path;
        });
    }])
    // 权限管理的Controller,其中主要包含了权限,资源等管理
    .controller('RolesCtrl', ['app', 'restService', 'commonService', '$scope', '$uibModal', '$window', '$cookieStore', function (app, restService, commonService, $scope, $uibModal, $window, $cookieStore) {
        console.log('roles-ctrl');

        // 排序规则
        $scope.orderRuleRole = 'id';
        $scope.setOrderRuleRole = function (orderRuleRole) {
            $scope.orderRuleRole = orderRuleRole;
        };

        // 职位,权限,资源
        $scope.roleQuery = commonService.createPageQuery(1, 5, 5);
        $scope.permissionQuery = commonService.createPageQuery(1, 10, 5);
        $scope.resourceQuery = commonService.createPageQuery(1, 10, 10);

        // 查询所有职位
        $scope.listRoles = function (page) {
            $scope.roleQuery.setPage(page);
            restService.api.authorize.save({
                ID: 'listRoles'
            }, {
                page: $scope.roleQuery.page,
                pageSize: $scope.roleQuery.pageSize
            }, function (result) {
                if (app.catchResultCode(result['resultCode'])) {
                    $scope.roleQuery.catchResult(result);
                }
            });
        };

        $scope.listResources = function (page) {
            $scope.resourceQuery.setPage(page);
            restService.api.authorize.save({
                ID: 'listResources'
            }, {
                page: $scope.resourceQuery.page,
                pageSize: $scope.resourceQuery.pageSize
            }, function (result) {
                if (app.catchResultCode(result['resultCode'])) {
                    $scope.resourceQuery.catchResult(result);
                }
            });
        };

        $scope.listPermissions = function (page) {
            $scope.permissionQuery.setPage(page);
            restService.api.authorize.save({
                ID: 'listPermissions'
            }, {
                page: $scope.permissionQuery.page,
                pageSize: $scope.permissionQuery.pageSize
            }, function (result) {
                if (app.catchResultCode(result['resultCode'])) {
                    $scope.permissionQuery.catchResult(result);
                }
            });
        };


        /******* 选项卡标签 *******/
        $scope.active_tab = $cookieStore.get('roles-active_tab');
        $scope.onTab = function (active_tab) {
            switch (active_tab) {
                case 'role':
                    $scope.listRoles($scope.roleQuery.page);
                    break;
                case 'resource':
                    $scope.listResources($scope.resourceQuery.page);
                    break;
                case 'permission':
                    $scope.listPermissions($scope.permissionQuery.page);
                    break;
            }
        };
        $scope.switchTab = function (active_tab) {
            $scope.active_tab = active_tab;
            $cookieStore.put('roles-active_tab', active_tab);
            $scope.onTab(active_tab);
        };
        $scope.onTab($scope.active_tab);


        // 创建职位,这里将弹出模态框
        $scope.createRole = function () {
            var modalInstance = $uibModal.open({
                templateUrl: 'templates/template_role_create.html',
                controller: 'TRoleCreateCtrl',
                backdrop: 'static',
                resolve: {}
            });

            // 真正地创建职位
            modalInstance.result.then(function (role) {
                restService.api.authorize.save({ID: 'createRole'}, role,
                    function (result) {
                        if (app.catchResultCode(result['resultCode'])) {
                            $window.location.reload();
                        }
                    });
            }, function () {

            });
        };
        $scope.removeRole = function (role) {
            var content = '您确定要删除 <' + role.name + '> [' + role.description + '] 吗？\n';
            content += '此操作所涉及的数据不可恢复,请谨慎操作！\n';
            commonService.openMessageDialog('警告:', content, function () {
                restService.api.authorize.get({
                    ID: 'removeRole',
                    id: role.id
                }, function (result) {
                    if (app.catchResultCode(result['resultCode'])) {
                        // 执行成功则刷新此页面
                        $window.location.reload();
                    }
                });
            }, function () {
            });
        };
        $scope.alterRole = function (role) {
            role = angular.fromJson(angular.toJson(role));
            commonService.openJsonEditor('修改职位', role, function (json) {
                    restService.api.authorize.save({ID: 'alterRole'}, json,
                        function (result) {
                            if (app.catchResultCode(result['resultCode'])) {
                                commonService.toast.putOToast({
                                    method: 'success',
                                    info: '职位修改成功！'
                                });
                                $window.location.reload();
                            }
                        });
                }, function () {
                }
            );
        };

        $scope.createPermission = function () {
            var modalInstance = $uibModal.open({
                templateUrl: 'templates/template_permission_create.html',
                controller: 'TPermissionCreateCtrl',
                backdrop: 'static',
                resolve: {}
            });

            modalInstance.result.then(function (permission) {
                restService.api.authorize.save({ID: 'createPermission'}, permission,
                    function (result) {
                        if (app.catchResultCode(result['resultCode'])) {
                            $window.location.reload();
                        }
                    });
            }, function () {

            });
        };
        $scope.removePermission = function (permission) {
            var content = '您确定要删除 <' + permission.roleDescription + '> [' + permission.permission + '] 吗？\n';
            content += '此操作所涉及的数据不可恢复,请谨慎操作！\n';
            commonService.openMessageDialog('警告:', content, function () {
                restService.api.authorize.get({
                    ID: 'removePermission',
                    id: permission.id
                }, function (result) {
                    if (app.catchResultCode(result['resultCode'])) {
                        // 执行成功则刷新此页面
                        $window.location.reload();
                    }
                });
            }, function () {
            });
        };
        $scope.alterPermission = function (permission) {
            permission = angular.fromJson(angular.toJson(permission));
            commonService.openJsonEditor('修改权限', permission, function (json) {
                restService.api.authorize.save({ID: 'alterPermission'}, json,
                    function (result) {
                        if (app.catchResultCode(result['resultCode'])) {
                            $window.location.reload();
                        }
                    });
            }, function () {
            });
        };

        // 创建资源,这里将弹出模态框
        $scope.createResource = function () {
            commonService.openJsonEditor('创建资源', {
                name: '',
                type: '',
                description: '',
                available: true
            }, function (json) {
                restService.api.authorize.save({ID: 'createResource'}, json,
                    function (result) {
                        if (app.catchResultCode(result['resultCode'])) {
                            $window.location.reload();
                        }
                    });
            }, function () {
            });
        };
        $scope.alterResource = function (resource) {
            resource = angular.fromJson(angular.toJson(resource));
            commonService.openJsonEditor('修改资源', resource, function (json) {
                restService.api.authorize.save({ID: 'alterResource'}, json,
                    function (result) {
                        if (app.catchResultCode(result['resultCode'])) {
                            commonService.toast.putOToast({
                                method: 'success',
                                info: '资源修改成功！'
                            });
                            $window.location.reload();
                        }
                    });
            }, function () {
            });
        };
        $scope.removeResource = function (resource) {
            console.log(resource);

            var content = '您确定要删除 <' + resource.name + '> [' + resource.description + '] 吗？\n';
            content += '此操作所涉及的数据不可恢复,请谨慎操作！\n';
            commonService.openMessageDialog('警告:', content, function () {
                restService.api.authorize.get({
                    ID: 'removeResource',
                    id: resource.id
                }, function (result) {
                    if (app.catchResultCode(result['resultCode'])) {
                        $window.location.reload();
                    }
                });
            }, function () {
            });
        };
    }])
    .controller('TRoleCreateCtrl', ['$scope', '$uibModalInstance', function ($scope, $uibModalInstance) {
        $scope.role = {
            type: '',
            name: '',
            description: '',
            available: true
        };
        $scope.create = function () {
            if ($scope.role.type == null || $scope.role.type.length == 0) {
                window.alert("TYPE不能是空的！");
                return;
            }
            if ($scope.role.name == null || $scope.role.name.length == 0) {
                window.alert("名称不能是空的！");
                return;
            }
            $uibModalInstance.close($scope.role);
        };
        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };
    }])
    .controller('TPermissionCreateCtrl', ['app', '$scope', '$uibModalInstance', 'restService', function (app, $scope, $uibModalInstance, restService) {
        $scope.roles = [];
        $scope.resources = [];
        $scope.role = null;
        $scope.resource = null;
        $scope.permission = null;
        $scope.available = true;

        $scope.setRole = function (role) {
            $scope.role = role;
        };
        $scope.setResource = function (resource) {
            $scope.resource = resource;
            $scope.permission = resource.name + ':';
        };

        $scope.allRoles = function () {
            restService.api.authorize.get({ID: 'listRoles'}, function (result) {
                if (app.catchResultCode(result['resultCode'])) {
                    $scope.roles = result.data;
                    if ($scope.roles.length > 0) {
                        $scope.setRole($scope.roles[0]);
                    }
                }
            });
        };
        $scope.allResources = function () {
            restService.api.authorize.get({ID: 'listResources'}, function (result) {
                if (app.catchResultCode(result['resultCode'])) {
                    $scope.resources = result.data;
                    if ($scope.resources.length > 0) {
                        $scope.setResource($scope.resources[0]);
                    }
                }
            });
        };

        $scope.create = function () {
            if ($scope.role == null || $scope.resource == null || $scope.permission == null) {
                window.alert("参数错误！");
                return;
            }
            $uibModalInstance.close({
                role: $scope.role,
                resource: $scope.resource,
                permission: $scope.permission,
                available: $scope.available
            });
        };
        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };

        $scope.allRoles();
        $scope.allResources();
    }]);